package com.dev.ac.web.server;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.map.MapUtil;
import com.dev.ac.common.Result;
import com.dev.ac.service.AAdminService;
import com.dev.ac.service.AUserService;
import com.dev.ac.util.RedisUtil;
import com.dev.ac.vo.LoginVo;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author 付
 * @Date 2024-04-14 16:23
 * @Version 1.0
 * @description
 * @since 1.0
 */
@RestController
@RequestMapping("/admin")
public class AdminLoginController {
	@Autowired
	AAdminService aAdminService;
	// 导入谷歌验证码工具
	@Resource
	Producer producer;
	@Autowired
	RedisUtil redisUtil;

	@PostMapping("/login")
	public Result login(@Validated @RequestBody LoginVo loginVo) {
		Object obj = aAdminService.login(loginVo);
		return Result.success(obj);
	}

	// 生成验证码图片
	@GetMapping("/captcha")
	public Result getCaptcha() throws IOException {
		// 生成uuid
		String uuid = UUID.randomUUID().toString();
		// 生成验证码
		String code = producer.createText();

		System.out.println("uuid=" + uuid + "----" + "code=" + code);
//		生成base64编码的图片验证码
		BufferedImage image = producer.createImage(code);
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", byteArrayOutputStream);

		String base64Img = "data:image/jpeg;base64," + Base64Encoder.encode(byteArrayOutputStream.toByteArray());

		// 把uuid和验证码存储到redis
		redisUtil.setEx(uuid, code, 120, TimeUnit.SECONDS);
		System.out.println(redisUtil);
		System.out.println("redis获取key---" + redisUtil.get(uuid));
		// 返回uuid和base64编码
		return Result.success(MapUtil.builder().put("uuid", uuid).put("base64Img", base64Img).build());
	}
}
